<template>
  <div
    class="micro-container"
  >
    <div id="app1"></div>
    <div id="app2"></div>
    <div id="subapp1"></div>
    <div id="subapp2"></div>
  </div>
</template>

<script setup lang='ts'>
import {watch, reactive, onMounted, onUnmounted} from 'vue'
import {useMicroAppStore} from '@/store'
import { useRoute } from 'vue-router'
import {loadMicroApp} from 'qiankun'

const microStore = useMicroAppStore()

const microApps = microStore.MICRO_APP_CONFIG

console.log('>>> microApps', microApps)

const route = useRoute()
const microList = reactive({})

const activationHandleChange = async (path) => {
  const activeRules = microApps.map((app) => app.activeRule)
  const isMicro = activeRules.some((rule) => typeof rule === 'function' ? rule(path) : path.startsWith(rule))
  if (!isMicro) return
  const microItem = microApps.find((app) => path.startsWith(app.activeRule.toString()))
  if (!microItem) return
  // 如果已经加载过一次，则无需再次加载
  const current = microList[microItem.activeRule.toString()]
  if (current) return

  // 缓存当前子应用
  const micro = loadMicroApp({ ...microItem })
  microList[microItem.activeRule.toString()] = micro
  try {
    await micro.mountPromise
  } catch (e) {
    console.error('=======', e)
  }
}

onMounted(async () => {
  console.log('MicroApp ======> 进入')
  if (window.qiankunStarted) return
  window.qiankunStarted = true
  // registerApps()
  activationHandleChange(route.path)
})
onUnmounted(() => {
  window.qiankunStarted = false
  Object.values(microList).forEach((mic) => {
    mic.unmount()
  })
})

watch(() => route.path, async (newValue) => {
  activationHandleChange(newValue)
})
</script>